package com.zdy.im.tio.command.handler;


import com.sixeco.framework.common.api.ApiDoc;
import com.sixeco.framework.util.json.JsonUtils;
import com.zdy.im.chat.ChatMessageBody;
import com.zdy.im.common.exception.ImException;
import com.zdy.im.core.ICommand;
import com.zdy.im.core.ImStatus;
import com.zdy.im.tio.command.AbstractCommandHandler;
import com.zdy.im.tio.command.Command;
import com.zdy.im.tio.packets.CloseBodyResponseVo;
import com.zdy.im.tio.packets.SocketResponseVo;
import org.springframework.stereotype.Component;
import org.tio.core.ChannelContext;
import org.tio.core.Tio;
import org.tio.core.intf.Packet;
import org.tio.http.common.HttpRequest;

/**
 * 版本: [1.0]
 * 功能说明: 关闭请求cmd命令处理器
 * @Author 作者 : zdy
 * @CreateDate 创建时间: 2021-02-30
 */
@Component
@ApiDoc(module = "WebSocket 项目文档",group = "SOCKET-GROUP")
public class CloseRequestHandler extends AbstractCommandHandler
{

	@Override
	public ICommand command() {
		return Command.COMMAND_CLOSE_REQ;
	}

	@ApiDoc(
			cmd = "15",methodType = "ws",
			value = "关闭请求,协议码cmd=15",
			request = CloseBodyResponseVo.class,
			response = ChatMessageBody.class
	)
	@Override
	public Packet handler(Packet packet, ChannelContext imChannelContext) throws ImException
	{
		CloseBodyResponseVo closeReqBody;
		try{
			HttpRequest wsRequest = (HttpRequest)packet;

			closeReqBody = JsonUtils.parseObject(wsRequest.getBody(),CloseBodyResponseVo.class);
		}catch (Exception e) {
			//关闭请求消息格式不正确
			SocketResponseVo respBody = new SocketResponseVo(Command.COMMAND_CLOSE_RESP, ImStatus.C10020);
			return this.converterWsResponse(respBody);
		}
		SocketResponseVo respBody = new SocketResponseVo(Command.COMMAND_CLOSE_RESP, ImStatus.C10021);
		respBody.setData(closeReqBody);
		Packet closePacket = this.converterWsResponse(respBody);
		Tio.bSend(imChannelContext,closePacket);
		Tio.remove(imChannelContext, "收到关闭请求!");

		return null;
	}


}
